package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.server.game.commondata.fight.*;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class FightBaseData {
    private static Logger logger = LoggerFactory.getLogger(FightBaseData.class);
    private static ConcurrentHashMap<Integer, Stage> stageMap = new ConcurrentHashMap<>(); // 主线关卡配置表
    private static ConcurrentHashMap<Integer, StageGuardItem> stageGuardItemMap = new ConcurrentHashMap<>(); // 关卡卫兵挂机的随机奖励
    private static ConcurrentHashMap<Integer, StageArea> stageAreaMap = new ConcurrentHashMap<>(); // 主线关卡区域配置表
    private static ConcurrentHashMap<Integer, MonsterTideMain> monsterTideMainMap = new ConcurrentHashMap<>(); // 兽潮配置表
    public static int maxMonsterTideId;// 兽潮最大的id
    private static ConcurrentHashMap<Integer, SnatchTransfer> snatchTransferMap = new ConcurrentHashMap<>(); // 物资争夺中转站等级配置表
    private static ConcurrentHashMap<Integer, SnatchFightReward> snatchFightRewardMap = new ConcurrentHashMap<>(); // 物资争夺战斗奖励贸易币




    // 公共数据初始化
    public static void init(List<Future> futures) {
        futures.add(initStage());
        futures.add(initStageArea());
        futures.add(initMonsterTideMain());
        futures.add(initSnatchTransfer());
        futures.add(initSnatchFightReward());
        futures.add(initStageGuardItem());
    }

    /**
     * 初始化主线关卡配置表
     */
    public static Future<Void> initStage() {
        String table = "stage";
        Promise promise = Promise.promise();
        String sql = "select * from " + table + ";";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getCommonPool(), sql, new JsonArray(), res -> {
            if (res.succeeded()) {
                try {
                    ConcurrentHashMap<Integer, Stage> tmp = new ConcurrentHashMap<>();
                    JsonArray result = res.result();
                    logger.info("init " + table + " size:" + result.size());
                    for (int i = 0; i < result.size(); i++) {
                        Stage entity = new Stage(result.getJsonObject(i));
                        tmp.put(entity.getId(), entity);
                    }
                    stageMap = tmp;
                    promise.complete();
                } catch (Exception e) {
                    logger.error("init " + table + " error exception:" + Tool.getException(e));
                    promise.fail(e);
                }
            } else {
                logger.error(res.cause().getMessage());
                promise.fail(res.cause());
            }
        });
        return promise.future();
    }

    public static Stage getStage(int id) {
        Stage result = stageMap.get(id);
        if (result == null) {
            logger.error("getStage error key = " + id);
        }
        return result;
    }
    public static ConcurrentHashMap<Integer, Stage> getStageMap() { return stageMap; }

    /**
     * 初始化主线关卡区域配置表
     */
    public static Future<Void> initStageArea() {
        String table = "stage_area";
        Promise promise = Promise.promise();
        String sql = "select * from " + table + ";";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getCommonPool(), sql, new JsonArray(), res -> {
            if (res.succeeded()) {
                try {
                    ConcurrentHashMap<Integer, StageArea> tmp = new ConcurrentHashMap<>();
                    JsonArray result = res.result();
                    logger.info("init " + table + " size:" + result.size());
                    for (int i = 0; i < result.size(); i++) {
                        StageArea entity = new StageArea(result.getJsonObject(i));
                        tmp.put(entity.getId(), entity);
                    }
                    stageAreaMap = tmp;
                    promise.complete();
                } catch (Exception e) {
                    logger.error("init " + table + " error exception:" + Tool.getException(e));
                    promise.fail(e);
                }
            } else {
                logger.error(res.cause().getMessage());
                promise.fail(res.cause());
            }
        });
        return promise.future();
    }

    public static StageArea getStageArea(int id) {
        StageArea result = stageAreaMap.get(id);
        if (result == null) {
            logger.error("getStageArea error key = " + id);
        }
        return result;
    }
    public static ConcurrentHashMap<Integer, StageArea> getStageAreaMap() { return stageAreaMap; }

    public static Stage getStage(int mapId, int stageId) {
        for (Stage stage : getStageMap().values()) {
            if (stage.getMapId() == mapId && stage.getStageId() == stageId) {
                return stage;
            }
        }
        return null;
    }


    //  获取某章节中的最大关卡
    public static Stage getMaxStageByMapId(int mapId) {
        int tmp = 0;
        Stage stage = null;
        for (Stage entity : getStageMap().values()) {
            if (entity.getMapId() == mapId && entity.getStageId() > tmp) {
                stage = entity;
                tmp = entity.getStageId();
            }
        }
        return stage;
    }



    public static StageArea getAreaByMapId(int mapId) {
        for (StageArea stageArea : getStageAreaMap().values())  {
            if (mapId >= stageArea.getMapIdStart() && mapId <= stageArea.getMapIdEnd()) {
                return stageArea;
            }
        }
        return null;
    }

    // 根据章节Id 获取stagearea
    public static StageArea getStageAreaByMapId(int mapId) {
        for (StageArea stageArea : getStageAreaMap().values()) {
            if (mapId >= stageArea.getMapIdStart() && mapId <= stageArea.getMapIdEnd()) {
                return stageArea;
            }
        }
        return null;
    }

    /**
     * 初始化兽潮配置表
     */
    public static Future<Void> initMonsterTideMain() {
        String table = "monster_tide_main";
        Promise promise = Promise.promise();
        String sql = "select * from " + table + ";";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getCommonPool(), sql, new JsonArray(), res -> {
            if (res.succeeded()) {
                try {
                    ConcurrentHashMap<Integer, MonsterTideMain> tmp = new ConcurrentHashMap<>();
                    JsonArray result = res.result();
                    logger.info("init " + table + " size:" + result.size());
                    for (int i = 0; i < result.size(); i++) {
                        MonsterTideMain entity = new MonsterTideMain(result.getJsonObject(i));
                        tmp.put(entity.getId(), entity);
                        if (entity.getId() > maxMonsterTideId) {
                            maxMonsterTideId = entity.getId();
                        }
                    }
                    monsterTideMainMap = tmp;
                    promise.complete();
                } catch (Exception e) {
                    logger.error("init " + table + " error exception:" + Tool.getException(e));
                    promise.fail(e);
                }
            } else {
                logger.error(res.cause().getMessage());
                promise.fail(res.cause());
            }
        });
        return promise.future();
    }

    public static MonsterTideMain getMonsterTideMain(int id) {
        MonsterTideMain result = monsterTideMainMap.get(id);
        if (result == null) {
            logger.error("getMonsterTideMain error key = " + id);
        }
        return result;
    }
    public static ConcurrentHashMap<Integer, MonsterTideMain> getMonsterTideMainMap() { return monsterTideMainMap; }


    /**
     * 初始化物资争夺中转站等级配置表
     */
    public static Future<Void> initSnatchTransfer() {
        String table = "snatch_transfer";
        Promise promise = Promise.promise();
        String sql = "select * from " + table + ";";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getCommonPool(), sql, new JsonArray(), res -> {
            if (res.succeeded()) {
                try {
                    ConcurrentHashMap<Integer, SnatchTransfer> tmp = new ConcurrentHashMap<>();
                    JsonArray result = res.result();
                    logger.info("init " + table + " size:" + result.size());
                    for (int i = 0; i < result.size(); i++) {
                        SnatchTransfer entity = new SnatchTransfer(result.getJsonObject(i));
                        tmp.put(entity.getId(), entity);
                    }
                    snatchTransferMap = tmp;
                    promise.complete();
                } catch (Exception e) {
                    logger.error("init " + table + " error exception:" + Tool.getException(e));
                    promise.fail(e);
                }
            } else {
                logger.error(res.cause().getMessage());
                promise.fail(res.cause());
            }
        });
        return promise.future();
    }

    public static SnatchTransfer getSnatchTransfer(int level) {
        for (SnatchTransfer snatchTransfer : getSnatchTransferMap().values()) {
            if (level == snatchTransfer.getLevel()) {
                return snatchTransfer;
            }
        }
        return null;
    }
    public static ConcurrentHashMap<Integer, SnatchTransfer> getSnatchTransferMap() { return snatchTransferMap; }

    /**
     * 初始化物资争夺战斗奖励贸易币
     */
    public static Future<Void> initSnatchFightReward() {
        String table = "snatch_fight_reward";
        Promise promise = Promise.promise();
        String sql = "select * from " + table + " order by ko_num_min asc;";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getCommonPool(), sql, new JsonArray(), res -> {
            if (res.succeeded()) {
                try {
                    ConcurrentHashMap<Integer, SnatchFightReward> tmp = new ConcurrentHashMap<>();
                    JsonArray result = res.result();
                    logger.info("init " + table + " size:" + result.size());
                    for (int i = 0; i < result.size(); i++) {
                        SnatchFightReward entity = new SnatchFightReward(result.getJsonObject(i));
                        tmp.put(entity.getId(), entity);
                    }
                    snatchFightRewardMap = tmp;
                    promise.complete();
                } catch (Exception e) {
                    logger.error("init " + table + " error exception:" + Tool.getException(e));
                    promise.fail(e);
                }
            } else {
                logger.error(res.cause().getMessage());
                promise.fail(res.cause());
            }
        });
        return promise.future();
    }

    public static SnatchFightReward getSnatchFightReward(int num) {
        for (SnatchFightReward snatchFightReward : getSnatchFightRewardMap().values()) {
            if (num >= snatchFightReward.getKoNumMin() && num <= snatchFightReward.getKoNumMax()) {
                return snatchFightReward;
            }
        }
        return null;
    }
    public static ConcurrentHashMap<Integer, SnatchFightReward> getSnatchFightRewardMap() { return snatchFightRewardMap; }

    //  统计这章节总的有多少小节
    public static int countNodeNum(int mapId) {
        int total = 0;
        for (Stage stage : getStageMap().values()) {
            if (stage.getMapId() == mapId) {
                total += stage.getNodeNum();
            }
        }
        return total;
    }

    /**
     * 初始化关卡卫兵挂机的随机奖励
     */
    public static Future<Void> initStageGuardItem() {
        String table = "stage_guard_item";
        Promise promise = Promise.promise();
        String sql = "select * from " + table + ";";
        MysqlTool.queryJsonArrayFromDb(MysqlClient.getCommonPool(), sql, new JsonArray(), res -> {
            if (res.succeeded()) {
                try {
                    ConcurrentHashMap<Integer, StageGuardItem> tmp = new ConcurrentHashMap<>();
                    JsonArray result = res.result();
                    logger.info("init " + table + " size:" + result.size());
                    for (int i = 0; i < result.size(); i++) {
                        StageGuardItem entity = new StageGuardItem(result.getJsonObject(i));
                        tmp.put(entity.getId(), entity);
                    }
                    stageGuardItemMap = tmp;
                    promise.complete();
                } catch (Exception e) {
                    logger.error("init " + table + " error exception:" + Tool.getException(e));
                    promise.fail(e);
                }
            } else {
                logger.error(res.cause().getMessage());
                promise.fail(res.cause());
            }
        });
        return promise.future();
    }

    public static StageGuardItem getStageGuardItem(int id) {
        StageGuardItem result = stageGuardItemMap.get(id);
        if (result == null) {
            logger.error("getStageGuardItem error key = " + id);
        }
        return result;
    }
    public static ConcurrentHashMap<Integer, StageGuardItem> getStageGuardItemMap() { return stageGuardItemMap; }

    public static List<StageGuardItem> getStageGuardItemList(int groupId) {
        List<StageGuardItem> result = new ArrayList<>();
        for (StageGuardItem stageGuardItem : getStageGuardItemMap().values()) {
            if (stageGuardItem.getGroupId() == groupId) {
                result.add(stageGuardItem);
            }
        }
        return result;
    }
}
